package com.aiapphub.BaseCode.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.aiapphub.BaseCode.entity.Role;
import com.aiapphub.BaseCode.entity.User;
import com.aiapphub.BaseCode.entity.UserRole;
import com.aiapphub.BaseCode.mapper.RoleMapper;
import com.aiapphub.BaseCode.mapper.UserMapper;
import com.aiapphub.BaseCode.mapper.UserRoleMapper;
import com.aiapphub.BaseCode.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 根据用户ID获取已分配的角色列表
     */
    @Override
    public List<Role> getAssignedRoles(Long userId) {
        List<Role> assignedRoles = new ArrayList<>();
        
        if (userId == null) {
            return assignedRoles;
        }
        
        // 查询用户已分配的角色ID列表
        List<Long> roleIdList = userRoleMapper.selectRoleIdsByUserId(userId);
        
        if (roleIdList != null && !roleIdList.isEmpty()) {
            // 根据角色ID列表查询角色信息，并过滤掉已删除的角色
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", roleIdList).eq("is_deleted", 0);
            assignedRoles = roleMapper.selectList(queryWrapper);
        }
        
        return assignedRoles;
    }
    
    @Transactional
    @Override
    public boolean removeRole(Long userId, Long roleId) {
        if (userId == null || roleId == null) {
            throw new IllegalArgumentException("用户ID和角色ID不能为空");
        }
        
        // 硬删除：直接从数据库中删除特定的用户角色关联
        int result = userRoleMapper.deleteByUserIdAndRoleId(userId, roleId);
        System.out.println("硬删除用户角色关联: userId=" + userId + ", roleId=" + roleId + ", 影响行数: " + result);
        
        return result > 0;
    }

    /**
     * 为用户分配角色
     */
    @Transactional
    @Override
    public boolean assignRolesToUser(Long userId, String roleIds) {
        try {
            if (userId == null) {
                throw new IllegalArgumentException("用户ID不能为空");
            }
            
            System.out.println("为用户ID: " + userId + " 分配角色: " + roleIds);
            
            // 1. 先清空用户所有角色关联（硬删除），确保彻底清除关联记录
            int deleteResult = userRoleMapper.deleteByUserId(userId);
            System.out.println("清空用户角色关联数量: " + deleteResult);
            
            // 2. 处理角色ID字符串，转换为Long集合并保存到数据库
            if (roleIds != null && !roleIds.isEmpty()) {
                String[] roleIdArray = roleIds.split(",");
                List<UserRole> userRoleList = new ArrayList<>();
                
                for (String roleIdStr : roleIdArray) {
                    try {
                        // 简单地将字符串转换为Long类型
                        String trimmedId = roleIdStr.trim();
                        System.out.println("处理角色ID字符串: " + trimmedId);
                        Long roleId = Long.parseLong(trimmedId);
                        System.out.println("解析角色ID: " + roleId);
                        
                        // 验证roleId是否存在于role表中且未被删除
                        Role role = roleMapper.selectById(roleId);
                        if (role != null && role.getIsDeleted() == 0) {
                            UserRole userRole = new UserRole();
                            userRole.setUserId(userId);
                            userRole.setRoleId(roleId);
                            userRole.setCreateTime(new Date());
                            userRole.setUpdateTime(new Date());
                            userRole.setDeleted(false);
                            userRoleList.add(userRole);
                            System.out.println("添加用户角色关联: userId=" + userId + ", roleId=" + roleId + ", 角色名称: " + role.getRoleName());
                        }
                    } catch (NumberFormatException e) {
                        System.err.println("角色ID格式错误: " + roleIdStr + ", 错误: " + e.getMessage());
                    }
                }
                
                // 3. 批量插入用户角色关联
                if (!userRoleList.isEmpty()) {
                    // 批量保存用户和角色的关联关系到数据库
                    System.out.println("准备批量插入，列表大小: " + userRoleList.size());
                    int insertResult = userRoleMapper.batchInsert(userRoleList);
                    System.out.println("成功保存的用户角色关联数量: " + insertResult);
                    return insertResult > 0;
                } else {
                    System.out.println("没有有效角色需要保存");
                    return true;
                }
            } else {
                System.out.println("角色ID字符串为空，已清空用户角色关联");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("分配角色失败", e);
        }
    }

    @Override
    public User getById(Long id) {
        // 简单实现，返回模拟数据
        User user = new User();
        user.setId(id);
        user.setUserName("用户" + id);
        return user;
    }

    @Override
    public boolean save(User user) {
        // 简单实现，返回成功
        System.out.println("保存用户: " + user);
        return true;
    }

    @Override
    public boolean update(User user) {
        // 简单实现，返回成功
        System.out.println("更新用户: " + user);
        return true;
    }

    @Override
    public boolean removeById(Long id) {
        // 简单实现，返回成功
        System.out.println("删除用户ID: " + id);
        return true;
    }
}